from django.db import models
from django.utils import timezone
import json

class Config(models.Model):
    """系统配置模型"""
    key = models.CharField(max_length=100, unique=True, verbose_name='配置键')
    value = models.JSONField(verbose_name='配置值')
    description = models.TextField(verbose_name='配置描述', blank=True, null=True)
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'config'
        verbose_name = '系统配置'
        verbose_name_plural = verbose_name
        ordering = ['key']

    def __str__(self):
        return f"{self.key} - {self.description or '无描述'}"

    @classmethod
    def get_value(cls, key, default=None):
        """获取配置值"""
        try:
            config = cls.objects.get(key=key)
            return config.value
        except cls.DoesNotExist:
            return default

    @classmethod
    def set_value(cls, key, value, description=None):
        """设置配置值"""
        config, created = cls.objects.update_or_create(
            key=key,
            defaults={
                'value': value,
                'description': description
            }
        )
        return config

    @classmethod
    def get_free_user_limits(cls):
        """获取免费用户限制"""
        return cls.get_value('free_user_limits', {
            'max_chars_per_request': 500,
            'max_requests_per_day': 10
        })

    @classmethod
    def get_vip_user_limits(cls):
        """获取VIP用户限制"""
        return cls.get_value('vip_user_limits', {
            'max_chars_per_request': 5000,
            'max_requests_per_day': 999999
        })

    @classmethod
    def get_payment_info(cls):
        """获取支付信息"""
        return cls.get_value('payment_info', {
            'wechat_qrcode': '',
            'alipay_qrcode': '',
            'price': {
                'monthly': 29.9,
                'yearly': 299
            }
        }) 